﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CML.Services.Interfaces;
using System.Xml;
using System.Xml.XPath;

namespace CML.Services.Implementations
{
	public class XmlService : IXmlService
	{
		public XmlNamespaceManager GetNamespaceManager(XPathNavigator n)
		{
			var manager = new XmlNamespaceManager(n.NameTable);
			n.MoveToRoot();
			var xmlnsList = new List<IDictionary<string, string>>();
			while (n.MoveToFollowing(XPathNodeType.Element))
			{
				xmlnsList.Add(n.GetNamespacesInScope(XmlNamespaceScope.All));
			}
			var result = xmlnsList.SelectMany(dict => dict)
						 .ToLookup(pair => pair.Key, pair => pair.Value)
						 .ToDictionary(group => group.Key, group => group.First());
			if (result != null)
			{
				foreach (var prefix in result.Keys)
				{
					manager.AddNamespace(prefix, result[prefix]);
				}
			}
			return manager;
		}

		public XmlDocument GetXmlFile(string fullPath)
		{
			var xml = new XmlDocument();
			xml.Load(fullPath);
			return xml;
		}
		

		
	}
}
